package com.doit.demo.day02.transformations;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.api.operators.StreamFilter;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * @DATE 2022/2/26/21:12
 * @Author MDK
 * @Version 2021.2.2
 *
 * StreamFilter的底层实现
 *
 **/
public class StreamFilterDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888);

        //输出以h开头的数据
        /*FilterFunction<String> filterFunction = new FilterFunction<String>() {
            @Override
            public boolean filter(String value) throws Exception {
                return value.startsWith("h");
            }
        };*/

        //SingleOutputStreamOperator<String> myFilter = lines.transform("MyFilter", TypeInformation.of(String.class), new StreamFilter<>(filterFunction));

        //自定义函数
        SingleOutputStreamOperator<String> myFilter = lines.transform("MyFilter", TypeInformation.of(String.class), new MyStreamFilter());


        myFilter.print();
        env.execute();
    }

    private static class MyStreamFilter extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String>{

        @Override
        public void processElement(StreamRecord<String> element) throws Exception {
            String word = element.getValue();
            if(word.startsWith("h")){
                output.collect(element);
            }
        }
    }
}
